package impl

import (
	"context"
	"errors"
	"time"
	"wms/entity"
	"wms/glo"
	"wms/service/model"
	"wms/service/request"
	"wms/util"

	"github.com/acmestack/gorm-plus/gplus"
)

type TenantService struct {
}

var TenantSrvImpl TenantService

func (s *TenantService) List(ctx context.Context, arg request.QueryTenantRequest) []*model.Tenant {
	var entities []*entity.Tenant
	_db := glo.Db_wms.Model(&entity.Tenant{})
	if arg.IsSupplier != nil {
		_db = _db.Where("is_supplier = ?", *arg.IsSupplier)
	}
	if arg.IsCustomer != nil {
		_db = _db.Where("is_customer = ?", *arg.IsCustomer)
	}
	if err := _db.Find(&entities).Error; err != nil {
		panic("sql err" + err.Error())
	}
	modelListOut := make([]*model.Tenant, 0, len(entities))
	for _, tmp := range entities {
		_w := new(model.Tenant)
		util.CopyStruct(_w, tmp)
		modelListOut = append(modelListOut, _w)
	}
	return modelListOut
}

func (s *TenantService) Add(ctx context.Context, arg *request.AddTenantRequest) error {
	addEntity := new(entity.Tenant)
	util.CopyStruct(addEntity, arg)
	resultDb := gplus.Insert(&addEntity)
	if resultDb.Error != nil {
		return errors.New("insert tenant err:" + resultDb.Error.Error())
	}
	util.Log("tenant id:", addEntity.TenantID)
	return nil
}

func (s *TenantService) Edit(ctx context.Context, arg *request.EditTenantRequest) error {
	editEntity, resultDb := gplus.SelectById[entity.Tenant](arg.TenantID)
	if resultDb.Error != nil {
		return errors.New("select tenant err:" + resultDb.Error.Error())
	}
	util.CopyStruct(editEntity, arg)
	editEntity.UpdatedAt = time.Now()
	util.Log("tenant arg:", *arg, "db:", *editEntity)
	resultDb = gplus.UpdateById(&editEntity)
	if resultDb.Error != nil {
		return errors.New("update tenant err:" + resultDb.Error.Error())
	}
	return nil
}
